package controller.services.interfaces;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import model.interfaces.DAOFactory;
import model.interfaces.HibernateGenericDAO;

public class JsfGenericService<T> implements GenericService<T> {
	// private ServiceFactory serviceFactory;
	// this.serviceFactory =
	// ServiceFactory.getServiceFactory(ServiceFactory.JSF);
	private DAOFactory daoFactory;
	private Class<T> persistentClass;
	private HibernateGenericDAO<T> daoClass;

	@SuppressWarnings("unchecked")
	public JsfGenericService() {
		this.daoFactory = DAOFactory.getDAOFactory(DAOFactory.HIBERNATE);
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		this.daoClass = daoFactory.getDAO(persistentClass);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T pesquisarPorId(Serializable id) {
		try {
			Class<T> t = (Class<T>) this.daoClass.pesquisarPorId(id);
			return (T) t;
		} finally {
			this.daoFactory.encerrar();
		}

	}

	public List<T> listarTodos() {
		try {
			List<T> ts = this.daoClass.listarTodos();
			return ts;

		} finally {
			this.daoFactory.encerrar();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public T salvar(T entidade) {
		this.daoFactory.iniciarTransacao();
		Class<T> t = (Class<T>) this.daoClass.salvar(entidade);
		this.daoFactory.encerrar();
		return (T) t;
	}

	@Override
	public void excluir(T entidade) {
		this.daoClass.excluir(entidade);
		this.daoFactory.encerrar();
	}

	@Override
	public void alterar(T entidade) {
		this.daoFactory.iniciarTransacao();
		this.daoClass.alterar(entidade);
		this.daoFactory.encerrar();

	}

}
